<template>
    <div class="members-container">
        <!-- 搜索区域 -->
        <div class="search-area">
            <div class="search-item">
                <span class="label">群:</span>
                <el-select v-model="searchForm.groupId" placeholder="请选择要操作的群" class="search-input"
                    @change="handleGroupChange" :loading="groupLoading">
                    <el-option v-for="group in groupList" :key="group.groupId" :label="group.name"
                        :value="group.groupId" />
                </el-select>
            </div>
            <div class="search-item">
                <span class="label">用户id:</span>
                <el-input v-model="searchForm.userId" placeholder="请输入用户id" class="search-input" />
            </div>
            <div class="search-item">
                <span class="label">用户名:</span>
                <el-input v-model="searchForm.username" placeholder="请输入用户名" class="search-input" />
            </div>
            <div class="search-item">
                <span class="label">用户昵称:</span>
                <el-input v-model="searchForm.nickname" placeholder="请输入用户昵称" class="search-input" />
            </div>
            <el-button type="primary" :icon="Search" class="search-btn" @click="fetchMembers">查找</el-button>
        </div>

        <!-- 表格区域 -->
        <el-table :data="memberList" style="width: 100%" @selection-change="handleSelectionChange"
            :header-cell-style="{ background: '#f5f7fa', color: '#606266', fontWeight: 'normal' }" v-loading="loading">
            <el-table-column type="selection" width="45" />
            <el-table-column prop="group" label="群" min-width="150" />
            <el-table-column prop="nickname" label="昵称" min-width="150" />
            <el-table-column prop="username" label="用户名" min-width="150" />
            <el-table-column prop="userId" label="用户id" min-width="120" />
            <el-table-column prop="role" label="身份" width="100">
                <template #default="scope">
                    <el-tag :type="getRoleTagType(scope.row.role)" class="status-tag">
                        {{ scope.row.role }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isBot" label="是否为机器人" width="120">
                <template #default="scope">
                    <el-tag :type="scope.row.isBot ? 'success' : 'info'" class="status-tag">
                        {{ scope.row.isBot ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="isBotAdmin" label="机器人管理员" width="120">
                <template #default="scope">
                    <el-tag :type="isBotAdmin(scope.row) ? 'success' : 'info'" class="status-tag">
                        {{ isBotAdmin(scope.row) ? '是' : '否' }}
                    </el-tag>
                </template>
            </el-table-column>
            <el-table-column prop="points" label="积分" width="120">
                <template #default="scope">
                    <div class="points-cell">
                        <span>{{ scope.row.points || 0 }}</span>
                        <el-button type="primary" size="small" @click="openAdjustDialog(scope.row)" class="adjust-btn">
                            调整
                        </el-button>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="220">
                <template #default="scope">
                    <div class="action-buttons">
                        <el-button type="primary" size="small" @click="toggleBotAdmin(scope.row)"
                            :disabled="scope.row.isBot">
                            {{ isBotAdmin(scope.row) ? '取消管理员' : '设为管理员' }}
                        </el-button>
                        <el-button v-if="isBotAdmin(scope.row)" type="danger" size="small"
                            @click="clearAllPermissions(scope.row)" :disabled="scope.row.isBot">
                            清除所有权限
                        </el-button>
                    </div>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页区域 -->
        <div class="pagination-container" v-if="memberList.length > 0">
            <span class="total-text">共 {{ total }} 条</span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[20, 50, 100]"
                layout="prev, pager, next, sizes" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" background class="custom-pagination" />
        </div>

        <!-- 无数据提示 -->
        <el-empty v-if="!loading && memberList.length === 0" description="暂无成员数据，请先选择群组" />

        <!-- 积分调整对话框 -->
        <el-dialog v-model="adjustDialogVisible" title="详情" width="500px" :close-on-click-modal="false"
            class="custom-dialog">
            <el-tabs v-model="activeTab">
                <el-tab-pane label="编辑" name="edit">
                    <div class="form-group">
                        <div class="form-item">
                            <span class="label">会员:</span>
                            <el-input v-model="currentMember.username" readonly />
                        </div>
                        <div class="form-item">
                            <span class="label">昵称:</span>
                            <el-input v-model="currentMember.nickname" readonly />
                        </div>
                        <div class="form-item">
                            <span class="label">调整金额:</span>
                            <el-input-number v-model="adjustForm.points" :precision="0" />
                        </div>
                        <div class="form-item">
                            <span class="label">调整原因:</span>
                            <el-input v-model="adjustForm.reason" type="textarea" placeholder="必须填写调整原因" :rows="4" />
                        </div>
                    </div>
                </el-tab-pane>
            </el-tabs>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="adjustDialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitPointsAdjust" :disabled="!adjustForm.reason">
                        确定
                    </el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { Search } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getGroups, getGroupMembers, setUserBotAdmin, clearUserAdminPermissions } from '../../api/group'
import { adjustPoints } from '../../api/points' // 引入积分调整API

export default {
    name: 'Members',
    setup() {
        // 数据部分
        const searchForm = ref({
            groupId: '',
            userId: '',
            username: '',
            nickname: ''
        })
        const memberList = ref([])
        const groupList = ref([])
        const currentPage = ref(1)
        const pageSize = ref(20)
        const total = ref(0)
        const loading = ref(false)
        const groupLoading = ref(false)
        let pollingTimer = null
        const currentGroup = ref(null) // 当前选中的群组

        // 积分调整相关
        const adjustDialogVisible = ref(false)
        const activeTab = ref('edit')
        const currentMember = ref({})
        const adjustForm = ref({
            points: 0,
            reason: ''
        })

        // 获取群组列表
        const fetchGroups = async () => {
            groupLoading.value = true
            try {
                const res = await getGroups()
                if (res.data.success) {
                    groupList.value = res.data.data
                    // 如果有群组数据且未选择过群组，则自动选择第一个
                    if (groupList.value.length > 0 && !searchForm.value.groupId) {
                        searchForm.value.groupId = groupList.value[0].groupId
                        await fetchMembers()
                    }
                } else {
                    ElMessage.error(res.data.message || '获取群组列表失败')
                }
            } catch (error) {
                console.error('获取群组列表错误:', error)
                ElMessage.error('获取群组列表失败，请稍后重试')
            } finally {
                groupLoading.value = false
            }
        }

        // 启动定时轮询
        const startPolling = () => {
            // 如果已选择群组，每30秒自动刷新一次数据
            if (searchForm.value.groupId) {
                pollingTimer = setInterval(fetchMembers, 30000)
            }
        }

        // 停止轮询
        const stopPolling = () => {
            if (pollingTimer) {
                clearInterval(pollingTimer)
                pollingTimer = null
            }
        }

        // 处理群组变更
        const handleGroupChange = async () => {
            // 清空成员列表
            memberList.value = []
            // 重置分页
            currentPage.value = 1
            // 停止之前的轮询
            stopPolling()
            // 获取当前选中的群组信息
            currentGroup.value = groupList.value.find(g => g.groupId === searchForm.value.groupId) || null
            // 加载该群组的成员
            await fetchMembers()
            // 启动新的轮询
            startPolling()
        }

        // 判断用户是否是机器人管理员
        const isBotAdmin = (member) => {
            if (!currentGroup.value || !member) return false
            return currentGroup.value.adminUsers && currentGroup.value.adminUsers.includes(member.userId)
        }

        // 切换用户的机器人管理员状态
        const toggleBotAdmin = async (member) => {
            if (!member || !searchForm.value.groupId) return

            try {
                loading.value = true
                const isAdmin = !isBotAdmin(member)
                const res = await setUserBotAdmin(searchForm.value.groupId, member.userId, isAdmin)

                if (res.data && res.data.success) {
                    ElMessage.success(res.data.message || `${isAdmin ? '设置' : '取消'}机器人管理员成功`)
                    // 更新当前群组信息
                    await fetchGroups()
                    currentGroup.value = groupList.value.find(g => g.groupId === searchForm.value.groupId) || null
                } else {
                    ElMessage.error(res.data?.message || `${isAdmin ? '设置' : '取消'}机器人管理员失败`)
                }
            } catch (error) {
                console.error(`${isBotAdmin(member) ? '取消' : '设置'}机器人管理员失败:`, error)
                ElMessage.error(`${isBotAdmin(member) ? '取消' : '设置'}机器人管理员失败，请稍后重试`)
            } finally {
                loading.value = false
            }
        }

        // 强制清除用户在所有群组中的管理员权限
        const clearAllPermissions = async (member) => {
            if (!member) return

            try {
                // 确认操作
                await ElMessageBox.confirm(
                    `确定要清除用户 ${member.username || member.userId} 在所有群组中的机器人管理员权限吗？此操作不可恢复。`,
                    '警告',
                    {
                        confirmButtonText: '确定清除',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }
                )

                loading.value = true
                const res = await clearUserAdminPermissions(member.userId)

                if (res.data && res.data.success) {
                    const affectedGroups = res.data.groupsAffected || []
                    ElMessage.success(`成功清除用户在 ${affectedGroups.length} 个群组中的管理员权限`)

                    // 更新群组信息
                    await fetchGroups()
                    currentGroup.value = groupList.value.find(g => g.groupId === searchForm.value.groupId) || null
                } else {
                    ElMessage.error(res.data?.message || '清除管理员权限失败')
                }
            } catch (error) {
                if (error !== 'cancel') {
                    console.error('清除管理员权限失败:', error)
                    ElMessage.error('清除管理员权限失败，请稍后重试')
                }
            } finally {
                loading.value = false
            }
        }

        // 获取群成员
        const fetchMembers = async () => {
            // 确保已选择群组
            if (!searchForm.value.groupId) {
                ElMessage.warning('请先选择群组')
                return
            }

            loading.value = true
            memberList.value = []

            try {
                const params = {
                    page: currentPage.value,
                    limit: pageSize.value,
                    userId: searchForm.value.userId,
                    username: searchForm.value.username,
                    nickname: searchForm.value.nickname
                }

                const res = await getGroupMembers(searchForm.value.groupId, params)
                if (res.data.success) {
                    memberList.value = res.data.data
                    total.value = res.data.pagination.total

                    // 如果搜索结果为空但使用了搜索条件，提示用户
                    if (memberList.value.length === 0 && (searchForm.value.userId || searchForm.value.username || searchForm.value.nickname)) {
                        ElMessage.info('没有找到匹配的成员')
                    }
                } else {
                    ElMessage.error(res.data.message || '获取群成员失败')
                }
            } catch (error) {
                console.error('获取群成员错误:', error)
                ElMessage.error('获取群成员失败，请稍后重试')
            } finally {
                loading.value = false
            }
        }

        // 角色样式
        const getRoleTagType = (role) => {
            switch (role) {
                case '群主': return 'success'
                case '管理': return 'warning'
                default: return 'info'
            }
        }

        // 表格选择变更
        const handleSelectionChange = (selection) => {
            console.log('选中的行:', selection)
        }

        // 分页条数变更
        const handleSizeChange = async (val) => {
            pageSize.value = val
            await fetchMembers()
        }

        // 页码变更
        const handleCurrentChange = async (val) => {
            currentPage.value = val
            await fetchMembers()
        }

        // 打开积分调整对话框
        const openAdjustDialog = (row) => {
            currentMember.value = { ...row }
            adjustForm.value = {
                points: 0,
                reason: ''
            }
            adjustDialogVisible.value = true
            activeTab.value = 'edit'
        }

        // 提交积分调整
        const submitPointsAdjust = async () => {
            if (!adjustForm.value.reason) {
                ElMessage.warning('请填写调整原因')
                return
            }

            if (adjustForm.value.points === 0) {
                ElMessage.warning('调整金额不能为0')
                return
            }

            try {
                const res = await adjustPoints({
                    groupId: currentMember.value.groupId,
                    userId: currentMember.value.userId,
                    points: adjustForm.value.points,
                    reason: adjustForm.value.reason
                })

                if (res.data.success) {
                    ElMessage.success('积分调整成功')
                    // 关闭对话框
                    adjustDialogVisible.value = false
                    // 刷新数据
                    fetchMembers()
                } else {
                    ElMessage.error(res.data.message || '积分调整失败')
                }
            } catch (error) {
                console.error('积分调整失败:', error)
                ElMessage.error('积分调整失败，请稍后重试')
            }
        }

        // 组件挂载时获取数据
        onMounted(() => {
            fetchGroups()
        })

        // 组件卸载前停止轮询
        onBeforeUnmount(() => {
            stopPolling()
        })

        return {
            searchForm,
            memberList,
            groupList,
            currentPage,
            pageSize,
            total,
            loading,
            groupLoading,
            Search,
            getRoleTagType,
            fetchGroups,
            fetchMembers,
            handleGroupChange,
            handleSelectionChange,
            handleSizeChange,
            handleCurrentChange,
            adjustDialogVisible,
            activeTab,
            currentMember,
            adjustForm,
            openAdjustDialog,
            submitPointsAdjust,
            isBotAdmin,
            toggleBotAdmin,
            clearAllPermissions
        }
    }
}
</script>

<style scoped>
.members-container {
    background-color: #fff;
    border-radius: 2px;
    padding: 15px;
}

.search-area {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 15px;
    flex-wrap: wrap;
}

.search-item {
    display: flex;
    align-items: center;
}

.label {
    font-size: 13px;
    color: #606266;
    margin-right: 8px;
}

.search-input {
    width: 180px;
}

.search-btn {
    height: 32px;
    padding: 0 15px;
    font-size: 13px;
}

.pagination-container {
    margin-top: 15px;
    display: flex;
    justify-content: flex-end;
    align-items: center;
}

.total-text {
    margin-right: 12px;
    color: #606266;
    font-size: 13px;
}

:deep(.el-table) {
    --el-table-border-color: #ebeef5;
    font-size: 13px;
}

:deep(.el-table th) {
    font-weight: normal;
    height: 40px;
    padding: 8px 0;
}

:deep(.el-table td) {
    padding: 8px 0;
}

:deep(.el-checkbox__inner) {
    width: 14px;
    height: 14px;
}

:deep(.status-tag) {
    height: 22px;
    padding: 0 8px;
    font-size: 12px;
}

:deep(.el-pagination) {
    font-size: 13px;
}

:deep(.el-pagination .el-select .el-input) {
    width: 100px;
}

:deep(.el-pagination button) {
    min-width: 28px;
    height: 28px;
}

:deep(.el-pagination .el-select .el-input__inner) {
    height: 28px;
}

:deep(.el-button--primary) {
    --el-button-bg-color: #1890ff;
    --el-button-border-color: #1890ff;
    --el-button-hover-bg-color: #40a9ff;
    --el-button-hover-border-color: #40a9ff;
}

:deep(.action-btn) {
    padding: 0;
    font-size: 13px;
}

:deep(.el-input__inner) {
    height: 32px;
}

:deep(.el-select__caret) {
    height: 32px;
    line-height: 32px;
}

/* 积分调整相关样式 */
.points-cell {
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.adjust-btn {
    margin-left: 8px;
    padding: 2px 6px;
    font-size: 12px;
    height: 24px;
}

.form-group {
    padding: 10px 0;
}

.form-item {
    margin-bottom: 18px;
    display: flex;
    align-items: flex-start;
}

.form-item .label {
    width: 80px;
    text-align: right;
    padding-right: 12px;
    line-height: 32px;
}

.form-item :deep(.el-input),
.form-item :deep(.el-input-number) {
    flex: 1;
}

.dialog-footer {
    display: flex;
    justify-content: flex-end;
}

/* 操作按钮样式 */
.action-buttons {
    display: flex;
    flex-wrap: wrap;
    gap: 5px;
}

.action-buttons .el-button {
    margin: 0;
    padding: 4px 8px;
    font-size: 12px;
}
</style>